When David wrote Psalm 31 is a matter of speculation, as are most of his psalms.
At a guess, it was written during his flight from Saul, and based on verse 21, perhaps after his flight from Keilah. (1 Samuel 23)
This is purely speculative, however.
The things that strike me from this psalm is that in the midst of his pleas for help, David time and again affirms his complete trust in God.
He says,
Into your hands I commit my spirit;
redeem me, O LORD, the God of truth. (Psalm 31:5)
And again,
I trust in you, O LORD;
I say, “You are my God.”
My times are in your hands. (Psalm 31:14–15)
All of ourselves go through struggles in our lives. And it’s so easy to place ourselves in our own hands. To take the driver’s seat of our lives and try to control our situation ourselves.
But in life and in death, David fully committed himself to God.
He said, “My life is in your hands, Lord. People are trying to kill me, but I know that as long as you want me here, they will not succeed. I refuse to take control of my own life, even if it costs me my life.”
And you see on two occasions in 1 Samuel where David had the chance to take control of the situation, to kill Saul and put an end to his vendetta against David. But David refused.
Jesus showed this same submission to his Father when he went to the cross. Though not strictly a Messianic psalm, nevertheless, you see some glimpses of Christ in David’s experience.
Like David, he was a man of sorrows and familiar with suffering. (Psalm 31:10)
Like David, he was despised. (Psalm 31:11)
Like David, he was abandoned by those he called friends. (Psalm 31:11–12)
Like David, people slandered him and plotted to kill him. (13)
Like David, he cried out, “My God, why have you forsaken me!” (22)
But like David, Jesus refused to take things into his own hands. He placed himself in his Father’s hands, and with his dying breath, quoted verse 5, saying, “Into your hands, I commit my spirit.”
And because of his submission, we have hope.
Hope that we will ultimately not be put to shame for trusting in him (17).
Hope in his goodness toward us (19).
And hope in our salvation (22–23).
So let us cry out as David did,
Be strong and take heart,
all you who hope in the LORD. (Psalm 31:24)
And let us put our full trust in him.
